package ar.edu.itba.bundundu;

import java.io.IOException;
import java.net.URL;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ar.edu.itba.bundundu.dao.UserDao;
import ar.edu.itba.bundundu.domain.UserIds;

import com.google.code.facebookapi.FacebookParam;
import com.google.gdata.client.calendar.CalendarService;
import com.google.gdata.data.calendar.CalendarFeed;

@SuppressWarnings("serial")
public class ShowCalendarsServlet extends HttpServlet {

  private static final long serialVersionUID = 1L;

  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    this.doGet(req, resp);
  }

  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    RequestDispatcher dispatcher;
    dispatcher = getServletContext().getRequestDispatcher("/showcalendars.jsp");

    try {
      // pedir el facebook uid
      Facebook facebook = new Facebook(req
          .getParameter(FacebookParam.SESSION_KEY.toString()));
      Long uid = facebook.getUserId();

      // levantar de la base el token para google calendar
      UserIds user = UserDao.getUser(uid);
      String sessionToken = user.getToken();
      // TODO: guardar el token en la session!

      // Send the request and print the response
      CalendarService calendar = new CalendarService("exampleCo-exampleApp-1");
      calendar.setAuthSubToken(sessionToken, null);
      URL feedUrl = new URL(
          "http://www.google.com/calendar/feeds/default/allcalendars/full");
      CalendarFeed resultFeed = calendar.getFeed(feedUrl, CalendarFeed.class);

      req.setAttribute("resultFeed", resultFeed);

      dispatcher.forward(req, resp);
    } catch (Exception e) {
      //e.printStackTrace();
    //TODO manejar esto bien cuando hay una exception (mandar un error en el req y atraparlo desde el jsp)
    }
  }

}
